<?php
/**
 * Created by PhpStorm.
 * User: HeiYanHeiMao
 * Date: 2020/2/27
 * Time: 17:46
 */

namespace app\model;


use think\facade\Db;
use think\facade\Cache;
use \think\response\Json;
use \Exception;

class GoodsModel
{
    private static $_table = 'eb_goods'; // 商品表
    private static $_storeTable = 'eb_store'; // 商户表
    private static $_schoolTable = 'eb_school'; // 学校表
    private static $_schoolStoreTable = 'eb_school_store'; // 学校商户关联表
    private static $_cateTable = 'eb_category'; // 商品分类表
    private static $_adminTable = 'eb_admin'; // 商品分类表

    /**商户添加商品
     * @param array $input 添加的数据
     * @param string $token token
     * @return Json
     */
    public static function add($input, $token)
    {
        try {
            // 判断商户是否有效
            $storeId = Cache::store('redis')->handler()->get($token);
            if (!$storeId) return jsonFail('获取商户信息失败');
            $storeStatus = Db::table(self::$_storeTable)->where('id', $storeId)->value('status');
            if ($storeStatus === null) return jsonFail('该商户不存在');
            // 0 未审核 1已审核 2审核未通过 3已禁用
            if ($storeStatus == 0) return jsonFail('该商户未审核,不能添加商品');
            if ($storeStatus == 2) return jsonFail('该商户审核未通过,不能添加商品');
            if ($storeStatus == 3) return jsonFail('该商户已禁用,不能添加商品');
            // 判断商品分类是否可用
            $cateInfo = Db::table(self::$_cateTable)->where('id', $input['cate_id'])->value('id');
            if ($cateInfo === null ) return jsonFail('无效的商品分类,不能添加商品');
            if($input['type']==2 && $input['meat_num']==0 && $input['veg_num']==0) return jsonFail('商品为套餐时，个数不能为0喔');
            // 添加数据
            $input['store_id'] = $storeId;
            $input['create_time'] = time();
            $input['price'] = abs($input['price']);
            $input['veg_num'] = abs($input['veg_num']);
            $input['meat_num'] = abs($input['meat_num']);
            $input['stock'] = intval(abs($input['stock']));
            $rtn = Db::table(self::$_table)->insertGetId($input);
            if ($rtn ){
                $data = [
                    'id'=>$rtn,
                    'type'=>$input['type'],
                    'meat_num'=>$input['meat_num'],
                    'veg_num'=>$input['veg_num'],
                    'name'=>$input['name'],
                    'price'=>$input['price'],
                    'stock'=>$input['stock'],
                    ];
                $addRtn = Cache::store('redis')->handler()->hMset('dxsd-goods-' .$rtn,$data);
                if ($addRtn===true){
                    Db::commit();
                    return jsonSuccess('添加成功');
                } else {
                    Db::rollback();
                    return jsonFail('系统错误~');
                }
            } else{
                return jsonFail('添加失败');
            }
        } catch (Exception $e) {
            return jsonFail('服务内部错误~');
        }
    }

    /**列表
     * @param $input
     * @param $token
     * @return Json
     */
    public static function list($input, $token)
    {
        try {
            // 检测当前管理员状态
            $admin = AdminModel::getInfo($token, [1],[2]);
            if ($admin instanceof Json) return $admin;
            $map[] = ['sc.operate_id', '=', $admin['id']];
            if ($input['name'] !== '') $map[] = ['g.name', 'like', "%{$input['name']}%"];
            if ($input['shop_name'] !== '') $map[] = ['st.shop_name', 'like', "%{$input['shop_name']}%"];
            $field = 'g.id,st.shop_name,g.name,g.type,g.lunchbox_fee,g.lunchbox_type,FROM_UNIXTIME(g.create_time, "%Y-%m-%d %H:%i:%s") AS create_time';
            $table = Db::table(self::$_adminTable)->alias('a')
                ->Join([self::$_schoolTable => 'sc'], 'sc.operate_id = a.id')
                ->Join([self::$_schoolStoreTable => 'ss'], 'ss.school_id = sc.id')
                ->Join([self::$_storeTable => 'st'], 'st.id = ss.store_id')
                ->Join([self::$_table => 'g'], 'g.store_id = st.id')
                ->field($field)
                ->where($map);
            $count = $table->count();
            if ($count == 0) return jsonSuccess('获取成功！', ['count' => $count, 'data' => []]);
            $data = $table->order('g.create_time', 'desc')->page($input['page'], $input['limit'])->select()->toArray();
            return jsonSuccess('获取成功！', ['count' => $count, 'data' => $data]);
        } catch (Exception $e) {
            return jsonFail('服务内部错误~');
        }
    }
    /**设置餐盒费
     * @param $input
     * @param $token
     * @return Json
     */
    public static function setFee($input, $token)
    {
        $flag = false;
        try {
            // 检测当前管理员状态
            $admin = AdminModel::getInfo($token, [1], [2]);
            if ($admin instanceof Json) return $admin;
            Db::startTrans();
            $flag = true;
            $rtn = Db::table(self::$_table)->where('id', $input['id'])->update(['lunchbox_fee' => $input['lunchbox_fee']]);
            if (!$rtn) {
                Db::rollback();
                return jsonFail('操作失败');
            }
            // 写入缓存
            $rtn = Cache::store('redis')->handler()->hMset('dxsd-goods-' .$input['id'],['lunchbox_fee' => $input['lunchbox_fee']]);
            if ($rtn!==true){
                Db::rollback();
                return jsonFail('操作失败');
            }
            Db::commit();
            return jsonSuccess('操作成功');
        } catch (Exception $e) {
            if ($flag == true) Db::rollback();
            return jsonFail('服务内部错误~');
        }
    }

    /**餐盒费收取方设置
     * @param $input
     * @param $token
     * @return Json
     */
    public static function typeChange($input, $token)
    {
        $flag = false;
        try {
            // 检测当前管理员状态
            $admin = AdminModel::getInfo($token, [1], [2]);
            if ($admin instanceof Json) return $admin;
            Db::startTrans();
            $flag = true;
            $rtn = Db::table(self::$_table)->where('id', $input['id'])->update(['lunchbox_type' => $input['lunchbox_type']]);
            if (!$rtn) {
                Db::rollback();
                return jsonFail('操作失败');
            }
            // 写入缓存
            $rtn = Cache::store('redis')->handler()->hMset('dxsd-goods-' .$input['id'],['lunchbox_type' => $input['lunchbox_type']]);
            if ($rtn!==true){
                Db::rollback();
                return jsonFail('操作失败');
            }
            Db::commit();
            return jsonSuccess('操作成功');
        } catch (Exception $e) {
            if ($flag == true) Db::rollback();
            return jsonFail('服务内部错误~');
        }
    }
}